package com.zd.kids.ui.fragment;

import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.Utils;
import com.hyy.libray.common.BaseUtils;
import com.hyy.libray.presenter.IBasePresenter;
import com.hyy.libray.ui.fragment.BaseFragment;
import com.zd.kids.DataBean.BaseDataBean;
import com.zd.kids.DataBean.PicBookDataBean;
import com.zd.kids.R;
import com.zd.kids.common.Constants;
import com.zd.kids.common.GlideUtil;
import com.zd.kids.common.MAudioPlayer;
import com.zd.kids.net.CustomObserver;
import com.zd.kids.net.HttpMethod;
import com.zd.kids.ui.activity.PicBookActivity;
import com.zd.kids.ui.view.GradienTextView;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class PicBookFragment extends BaseFragment {

    @BindView(R.id.img_content)
    ImageView imgContent;
    @BindView(R.id.gradienTextView)
    GradienTextView gradienTextView;
    @BindView(R.id.rl_end)
    LinearLayout rlEnd;

    private PicBookDataBean.ResultBean dataBeas;

    private MAudioPlayer mOriginAudioPlayer;

    private boolean isLast;

    private String mUnitId;

    public PicBookFragment(PicBookDataBean.ResultBean resultBean) {
        this.dataBeas = resultBean;
    }

    public void setLast(boolean last) {
        isLast = last;
    }

    public void setUnitId(String mUnitId) {
        this.mUnitId = mUnitId;
    }

    /**
     * 获取布局文件地址
     */
    @Override
    public int getLayoutResId() {
        return R.layout.fragment_pic_book_blank;
    }


    @Override
    public void onPause() {
        super.onPause();
        mOriginAudioPlayer.pause();

        if (disposable != null) {
            disposable.dispose();
        }
        gradienTextView.stop();
    }


    @Override
    public void onResume() {
        super.onResume();

        gradienTextView.setText(dataBeas.getTitle());


        String fileName = dataBeas.getAudio_path().substring(dataBeas.getAudio_path().lastIndexOf("/"));
        mOriginAudioPlayer.playUrl(Constants.AUDIO_ROOT_PATH + fileName);

        if (rlEnd.getVisibility() == View.VISIBLE) {
            rlEnd.setVisibility(View.GONE);
        }
    }


    /**
     * 初始化布局
     *
     * @param view
     */
    @Override
    public void initView(View view) {

    }

    private long mAudioDuring;

    /**
     * 初始化数据
     */
    @Override
    public void initData() {

        GlideUtil.load(dataBeas.getImg_path(), imgContent);

        mOriginAudioPlayer = new MAudioPlayer();

        mOriginAudioPlayer.setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
            @Override
            public void playerPause() {
            }

            @Override
            public void playerCompletion(MediaPlayer mp) {
                if (isLast) {
                    rlEnd.setVisibility(View.VISIBLE);
                    setCompleteResult(mUnitId);
                }
            }

            @Override
            public void playerPrepared(MediaPlayer mp) {
                mAudioDuring = mp.getDuration();
                mp.start();
                if (mAudioDuring == -1) {
                    startintervalText(dataBeas.getTime() * 1000);
                } else {
                    startintervalText(mAudioDuring);
                }

            }

            @Override
            public void playerStart() {

            }

            @Override
            public void playerError(MediaPlayer mp, int what, int extra) {
            }
        });

    }

    /**
     * 获取Presenter，不用MVP，可以为空
     *
     * @return
     */
    @Override
    protected IBasePresenter onBasePresenter() {
        return null;
    }

    private Disposable disposable;

    private void startintervalText(long intervalTime) {
        Observable.timer(1000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        if (gradienTextView != null) {
                            gradienTextView.setText(dataBeas.getTitle());
                            gradienTextView.start(intervalTime - 1000);
                        }


                    }
                });
    }

    @OnClick({R.id.img_left, R.id.img_restart, R.id.img_leave, R.id.img_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_left:
                if (BaseUtils.isFastClick()) {
                    return;
                }

                leftContent();
                break;
            case R.id.img_right:
                if (BaseUtils.isFastClick()) {
                    return;
                }
                rightContent();
                break;
            case R.id.img_leave:
                getActivity().finish();
                break;
            case R.id.img_restart:
                startContent();
                break;
        }
    }

    private void leftContent() {
        if (getActivity() instanceof PicBookActivity) {
            ((PicBookActivity) getActivity()).leftContent();
        }


    }

    private void rightContent() {
        if (getActivity() instanceof PicBookActivity) {
            ((PicBookActivity) getActivity()).nextContent();
        }
    }

    private void startContent() {
        if (getActivity() instanceof PicBookActivity) {
            ((PicBookActivity) getActivity()).startContent();
        }
    }


    private void setCompleteResult(String unitid) {
        if (TextUtils.isEmpty(unitid)) {
            return;
        }

        HttpMethod.getIntence().setPicBookCompleteResult(unitid, new CustomObserver<BaseDataBean>(getContext()) {
            @Override
            public void onSuccess(BaseDataBean baseDataBean) {
                if (!TextUtils.isEmpty(mUnitId)) {
                    mUnitId = "";
                }

            }

            @Override
            public void onError(String errorCode) {

            }
        });

    }
}